<?php

namespace App\Services\Tool\Pay;
// header('Content-type: text/html; charset=GBK');

use App\Services\Tool\Pay\NetPayClient;
use Log;
include_once("netpayclient_config.php");
include_once("lib_curl.php");

class UnionChinaPay{

    private static $error = [
                                '0000' => '接收成功',
                                '0001' => '请求失败',
                                '0100' => '商户提交的字段长度、格式错误',
                                '0101' => '商户验签错误',
                                '0102' => '手续费计算出错',
                                '0103' => '商户备付金帐户金额不足',
                                '0104' => '操作拒绝',
                                '0105' => '重复交易'
                                ];

    function test($input = []){
        $obj = new NetPayClient();
        $merId = $obj->buildKey(PRI_KEY);
        //商户日期，本例采用当天日期，必填
        $merDate = date('Ymd');
        //生成流水号，定长16位，任意数字组合，一天内不允许重复，本例采用当前时间戳，必填
        $merSeqId = $input['merSeqId'];
        //收款账号，必填
        $cardNo = $input['accNo'];
        //收款人姓名，必填
        $usrName = $input['customerNm'];
        //开户银行,本例采用工商银行，必填
        $openBank = $input['bank_name'];
        //省份,本例采用上海，必填
        $prov = $input['prov'];
        //城市,本例采用上海，必填
        $city = $input['city'];
        //订单金额，变长12位，以分为单位，必填
        $transAmt = self::get_total_fee($input['total_fee']);"000000000001";
        //用途，可选
        $purpose = $input['purpose'];
        //支行,可选，参与签名
        // $subBank = "";
        //付款标志,"00"对私，"01"对公，如不填则默认为对私
        $flag = "00";
        //接口版本号，境内支付为 20090501，必填
        $termType = "08";
        //渠道类型，必填
        $version = "20160530";
        //签名标志，值固定，但不参与签名
        $signFlag = "1";
        //表示商户代付业务交易模式
        $payMode = "1";

        //按次序组合报文信息为待签名串
        $plain = $merId . $merDate  . $merSeqId . $cardNo . $usrName  . $openBank  . $prov  . $city  . $transAmt  . $purpose  . $flag  . $version . $termType . $payMode;

        $plain = iconv('UTF-8', 'GB2312', $plain);
        // echo $plain;
        //进行Base64编码
        $data = base64_encode($plain);
        //生成签名值，必填
        $chkValue = $obj->sign($data);
        if (!$chkValue) {
            return ['state' => 'M00001', 'message' => "签名失败！"];
            exit;
        }

        $usrName = urlencode(iconv('UTF-8', 'GB2312', $usrName));
        $openBank = urlencode(iconv('UTF-8', 'GB2312', $openBank));
        $prov = urlencode(iconv('UTF-8', 'GB2312', $prov));
        $city = urlencode(iconv('UTF-8', 'GB2312', $city));
        $purpose = urlencode(iconv('UTF-8', 'GB2312', $purpose));
        // $subBank = urlencode(iconv('UTF-8', 'GB2312', $subBank));

        $http = HttpInit();
        $post_data = "merId=$merId&merDate=$merDate&merSeqId=$merSeqId&cardNo=$cardNo&usrName=$usrName&openBank=$openBank&prov=$prov&city=$city&transAmt=$transAmt&purpose=$purpose&flag=$flag&version=$version&termType=$termType&payMode=$payMode&signFlag=$signFlag&chkValue=$chkValue";
        Log::info('==================================');
        Log::info($post_data);

        $output = HttpPost($http, $post_data, PAY_URL);
        Log::info($output);
        if($output){
            $output = trim(strip_tags($output));
            Log::info("<h2>交易返回</h2>");
            Log::info($output . "<br/>");
            Log::info("=================================<br/>");

            // echo "<h2>交易返回</h2>";
            // echo "$output<br/>";
            // echo "=================================<br/>";
            //开始解析数据
            $datas = explode("&",$output);
            foreach($datas as $data){
                Log::info("$data<br/>");
                // echo "$data<br/>";
            }
            Log::info("=================================<br/>");

            // echo "=================================<br/>";

            $dex = strripos($output,"&");
            $plain = substr($output,0,$dex);
            Log::info("验签明文：<br/>" . $plain . "<br/>");

            // echo "验签明文：<br/>" . $plain . "<br/>";
            $plaindata = base64_encode($plain);
            $resp_code = $data[0];
            $chkValue = substr($output,$dex+ 10);
            Log::info("chkValue值：<br/>" . $chkValue . "<br/>");
            // echo "chkValue值：<br/>" . $chkValue . "<br/>";

            //开始验证签名，首先导入公钥文件
            $flag = $obj->buildKey(PUB_KEY);
            if(!$flag) {
                Log::info("导入公钥文件失败！");
                // echo "导入公钥文件失败！";
                return ['state' => 'M00001','message'=>'导入公钥文件失败！'];
            } else {
                $flag  =  $obj->verify($plaindata, $chkValue);
                if($flag) {
                    //验证签名成功，
                    Log::info("<h4>Success</h4>");
                    // echo "<h4>Success</h4>";
                    //请把您自己需要处理的逻辑写在这里
                    $code = [];
                    foreach(explode("&",$output) as $one){
                        $arr = explode("=",$one);
                        if(isset($arr[0]) && isset($arr[1])){
                            $code[$arr[0]] = $arr[1];
                        }
                    }
                    return ['state' => (isset(self::$error[$code['responseCode']]) ? $code['responseCode'] : '0001'),
                            'message' => (isset(self::$error[$code['responseCode']]) ? self::$error[$code['responseCode']] : '未知错误')];
                } else {
                    Log::info("<h4>Fail</h4>");
                    // echo "<h4>Fail</h4>";
                    return ['state' => 'M00001','message'=>'验证签名失败'];
                }
            }
        }

    }

    static function get_total_fee($input){
        $total_fee = intval($input * 100).'';
        $length = mb_strlen($total_fee);
        $str = '';
        for($a = 0;$a<(12 - $length);$a++){
            $str .= '0';
        }
        return $str . $total_fee;
    }

    static function get_balance(){
        $obj = new NetPayClient();
        $merId = $obj->buildKey(PRI_KEY);
        //版本号
        $version = '20090501';
        //签名标志
        $signFlag = '1';

        //按次序组合报文信息为待签名串
        $plain = $merId . $version;

        $plain = iconv('UTF-8', 'GB2312', $plain);
        // echo $plain;
        //进行Base64编码
        $data = base64_encode($plain);
        //生成签名值，必填
        $chkValue = $obj->sign($data);
        if (!$chkValue) {
            return ['state' => 'M00001', 'message' => "签名失败！"];
            exit;
        }

        // $subBank = urlencode(iconv('UTF-8', 'GB2312', $subBank));

        $http = HttpInit();
        $post_data = "merId=$merId&version=$version&signFlag=$signFlag&chkValue=$chkValue";
        Log::info('==================================');
        Log::info($post_data);

        $output = HttpPost($http, $post_data, BALANCE_URL);
        Log::info($output);
        if($output){
            $result = explode('|',$output);
            $arr['code']  = $result[0];
            if($arr['code'] == '000'){
                return ($result[2]/100);
            }else{
                Log::info('获取储备金余额失败：');
                return 0;
            }
        }
    }
}
